package com.hmdp;

import java.sql.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class DatabaseMonitor {
    private static final String DB_URL = "jdbc:mysql://localhost:3306/madical?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "191224";

    private Connection connection;
    private long lastTimestamp;

    public void start() {
        try {
            connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
            lastTimestamp = System.currentTimeMillis();

            ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
            executor.scheduleAtFixedRate(this::checkForChanges, 0, 5, TimeUnit.SECONDS);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void checkForChanges() {
        try {
            String query = "SELECT * FROM patient WHERE type = 1 AND patient_id > ?";
            PreparedStatement statement = connection.prepareStatement(query);
            //statement.setInt(1, lastId);

            ResultSet resultSet = statement.executeQuery();
            while (resultSet.next()) {
                // 处理变化的数据
                int id = resultSet.getInt("id");
                String data = resultSet.getString("data");
                Timestamp updatedAt = resultSet.getTimestamp("updated_at");

                // 在此处执行所需的操作,例如打印或进一步处理数据
                System.out.println("Changed data: id=" + id + ", data=" + data + ", updated_at=" + updatedAt);
            }

            lastTimestamp = System.currentTimeMillis();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        DatabaseMonitor monitor = new DatabaseMonitor();
        monitor.start();
    }
}
